package com.ciquan.server.controller;

import com.ciquan.server.util.MD5Utils;
import com.ciquan.server.util.web.BasePathUtil;
import com.ciquan.server.util.web.PageUtil;
import com.ciquan.server.util.web.ParameterMap;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.ServletRequestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * Created by bjliwei2014 on 2015/1/8.
 */
public abstract class AbstractController {

    protected Logger logger = Logger.getLogger(this.getClass());

    protected int initPage(String page) {
        if(StringUtils.isBlank(page)) {
            return 1;
        }

        else {
            return Integer.valueOf(page);
        }
    }

    protected void parameterInit(HttpServletRequest request, ParameterMap parameterMap) {
        Enumeration enumeration = request.getParameterNames();
        while (enumeration.hasMoreElements()) {
            String name = (String) enumeration.nextElement();
            String value = request.getParameter(name);
            parameterMap.put(name, value);
        }
    }

    protected void parameterTrimInit(HttpServletRequest request, ParameterMap parameterMap) {
        Enumeration enumeration = request.getParameterNames();
        while (enumeration.hasMoreElements()) {
            String name = (String) enumeration.nextElement();
            String value = request.getParameter(name);
            if(StringUtils.isNotBlank(value)) {
                parameterMap.put(name, value);
            }
        }
    }

    protected void page(int count, int pageNum, String uri, ParameterMap parameterMap, HttpServletRequest request, ModelMap modelMap) {
        PageUtil pageUtil = new PageUtil();
        pageUtil.setItems(count);
        pageUtil.setItemsPerPage(20);
        pageUtil.setPage(pageNum);
        int startIndex = pageUtil.getBeginIndex() > 0 ? pageUtil
                .getBeginIndex() - 1 : pageUtil.getBeginIndex();

        modelMap.put(
                "page",
                pageUtil.toPageString(BasePathUtil.getBasePath(request) + uri,
                        "?" + parameterMap.bulidSearchParameter(), "self"));

        parameterMap.setStart(startIndex);
        parameterMap.setPageNum(20);
    }

    protected boolean isLogin(HttpServletRequest request) {
        String userId = ServletRequestUtils.getStringParameter(request, "userId", "");
        String hash = ServletRequestUtils.getStringParameter(request, "hash", "");
        return StringUtils.equalsIgnoreCase(hash, getUserHash(userId));
    }

    protected String getUserHash(String userid){
        String hash_key = "lkA*w42foahsdf9*Q@";
        String hash = MD5Utils.md5(userid + "_" + hash_key);
        return hash.toLowerCase();
    }
}
